#include "MDD.h"
#include <iostream>

// 构造函数
MDD::MDD(const std::string& fname, const std::pair<std::vector<uint8_t>, std::string>& passcode) 
    : MDictBase(fname, "UTF-8", passcode) {
    // MDD文件默认使用UTF-8编码
}

// 处理记录数据（MDD文件不需要样式替换）
std::vector<uint8_t> MDD::_treat_record_data(const std::vector<uint8_t>& data) {
    // MDD文件直接返回原始数据
    return data;
}

// 读取记录
std::vector<std::pair<std::string, std::vector<uint8_t>>> MDD::_read_records() {
    std::vector<std::pair<std::string, std::vector<uint8_t>>> result;
    
    if (m_version >= 3) {
        // v3版本实现（简化版）
        std::ifstream file(m_filename, std::ios::binary);
        if (!file) {
            throw std::runtime_error("Failed to open file: " + m_filename);
        }
        
        // 读取记录数据
        file.seekg(m_record_block_offset);
        uint32_t number = BinaryIO::read_value<uint32_t>(file);
        uint64_t total_size = BinaryIO::read_value<uint64_t>(file);
        
        // 处理每个记录块
        for (uint32_t i = 0; i < number; ++i) {
            uint32_t decompressed_size = BinaryIO::read_value<uint32_t>(file);
            uint32_t compressed_size = BinaryIO::read_value<uint32_t>(file);
            
            std::vector<uint8_t> block_data = BinaryIO::read_bytes(file, compressed_size);
            std::vector<uint8_t> decompressed_block_data = _decode_block(block_data, decompressed_size);
            
            // 简化实现：直接将整个块作为一个记录
            if (i < m_key_list.size()) {
                const std::string& key_text = m_key_list[i].second;
                std::vector<uint8_t> treated_data = _treat_record_data(decompressed_block_data);
                result.emplace_back(key_text, treated_data);
            }
        }
        
        file.close();
    } else {
        // v1/v2版本实现（与MDX类似，但不进行样式替换）
        std::ifstream file(m_filename, std::ios::binary);
        if (!file) {
            throw std::runtime_error("Failed to open file: " + m_filename);
        }
        
        file.seekg(m_record_block_offset);
        
        // 读取记录块信息
        int num_record_blocks = (m_version >= 2.0) ? BinaryIO::read_value<uint64_t>(file) : BinaryIO::read_value<uint32_t>(file);
        int num_entries = (m_version >= 2.0) ? BinaryIO::read_value<uint64_t>(file) : BinaryIO::read_value<uint32_t>(file);
        
        if (num_entries != m_num_entries) {
            throw std::runtime_error("Number of entries mismatch");
        }
        
        int record_block_info_size = (m_version >= 2.0) ? BinaryIO::read_value<uint64_t>(file) : BinaryIO::read_value<uint32_t>(file);
        int record_block_size = (m_version >= 2.0) ? BinaryIO::read_value<uint64_t>(file) : BinaryIO::read_value<uint32_t>(file);
        
        // 读取记录块信息列表
        std::vector<std::pair<uint64_t, uint64_t>> record_block_info_list;
        int size_counter = 0;
        
        for (int i = 0; i < num_record_blocks; ++i) {
            uint64_t compressed_size = (m_version >= 2.0) ? BinaryIO::read_value<uint64_t>(file) : BinaryIO::read_value<uint32_t>(file);
            uint64_t decompressed_size = (m_version >= 2.0) ? BinaryIO::read_value<uint64_t>(file) : BinaryIO::read_value<uint32_t>(file);
            record_block_info_list.emplace_back(compressed_size, decompressed_size);
            size_counter += m_number_width * 2;
        }
        
        if (size_counter != record_block_info_size) {
            throw std::runtime_error("Record block info size mismatch");
        }
        
        // 处理记录块
        long offset = 0;
        int i = 0;
        size_counter = 0;
        
        for (const auto& block_info : record_block_info_list) {
            uint64_t compressed_size = block_info.first;
            uint64_t decompressed_size = block_info.second;
            
            std::vector<uint8_t> record_block_data = BinaryIO::read_bytes(file, compressed_size);
            std::vector<uint8_t> record_block = _decode_block(record_block_data, static_cast<uint32_t>(decompressed_size));
            
            // 根据键块中的偏移信息分割记录块
            while (i < m_key_list.size()) {
                uint64_t record_start = m_key_list[i].first;
                const std::string& key_text = m_key_list[i].second;
                
                // 检查是否到达当前记录块的末尾
                if (record_start - offset >= record_block.size()) {
                    break;
                }
                
                // 确定记录结束位置
                uint64_t record_end;
                if (i < m_key_list.size() - 1) {
                    record_end = m_key_list[i + 1].first;
                } else {
                    record_end = record_block.size() + offset;
                }
                
                // 提取记录数据
                std::vector<uint8_t> data(record_block.begin() + (record_start - offset), 
                                         record_block.begin() + (record_end - offset));
                
                // 处理记录数据（MDD直接返回原始数据）
                std::vector<uint8_t> treated_data = _treat_record_data(data);
                
                // 添加到结果中
                result.emplace_back(key_text, treated_data);
                
                i++;
            }
            
            offset += record_block.size();
            size_counter += compressed_size;
        }
        
        if (size_counter != record_block_size) {
            throw std::runtime_error("Record block size mismatch");
        }
        
        file.close();
    }
    
    return result;
}

// 获取所有键值对
std::vector<std::pair<std::string, std::vector<uint8_t>>> MDD::items() {
    return _read_records();
}